package logic

import (
	"context"
	"encoding/json"
	"gitee.com/Cauchy_AQ/vxopen/model/mongodb"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/internal/types"
	"time"

	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/internal/svc"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/transform"

	"github.com/zeromicro/go-zero/core/logx"
)

type WsMessageHandlerLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewWsMessageHandlerLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WsMessageHandlerLogic {
	return &WsMessageHandlerLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *WsMessageHandlerLogic) WsMessageHandler(in *transform.WsMessageReq) (*transform.WsMessageResp, error) {
	var wsMessage types.WSMessage
	if err := json.Unmarshal(in.Message, &wsMessage); err != nil {
		return nil, err
	}
	wsMessage.Timestamp = time.Now().Unix()

	data := &mongodb.Chat{
		Message:   wsMessage.Message,
		Name:      wsMessage.Name,
		Avatar:    wsMessage.Avatar,
		Role:      wsMessage.Role,
		Timestamp: wsMessage.Timestamp,
	}
	mongoClient := mongodb.GetMongoInstance(l.svcCtx.Config.ModelConfig)
	if err := mongoClient.ChatCol.Insert(context.Background(), data); err != nil {
		return nil, err
	}

	b, _ := json.Marshal(data)
	return &transform.WsMessageResp{
		Message: b,
	}, nil
}
